package wangwenjun.phase2.concurrencypattern.eventrouter.demo03.framework;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ChangLiang
 * @date 2020/6/20
 */
public abstract class AsyncChannel<E extends Message> implements Channel<E> {

    /**
     * 在AsyncChannel 中将使用Executor Service 多线程的方式提交Message
     * 一个AsyncChannel对应一个线程池
     */
    private final ExecutorService executorService;

    /**
     * 默认构造函数， 提供了CPU 的核数× 2 的线程数量
     */
    public AsyncChannel() {
        this(Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2));
    }

    public AsyncChannel(ExecutorService executorService) {
        this.executorService = executorService;
    }

    /**
     * 使用final修饰 禁止子类override
     * @param message
     */
    @Override
    public final void dispatch(E message) {
        executorService.submit(() -> this.handle(message));
    }

    /**
     * 子类执行的方法 写在handle上
     * @param message
     */
    protected abstract void handle(E message);

    void stop() {
        if (null != executorService && !executorService.isShutdown()) {
            executorService.shutdown();
        }
    }
}
